<?php

namespace app\common\command;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\user\WalletLog;
use app\admin\model\user\Userfinancial;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\HttpResponseException;

class Release extends Command
{
    protected function configure()
    {
        $this->setName('release')->setHelp('理财产品返利')->setDescription('返利');
    }

    protected function execute(Input $input, Output $output)
    {
        $model = new Userfinancial();
//        $data  = $model->where('day_time','<',time())->select();
        $walletLog = new WalletLog();
//        $count     = $walletLog->whereTime('createtime', 'd')->where('event', '=', 'interest')->count();
//        if ($count) {
//            echo '今日已经返利';
//            return;
//        }
        $data = $model->with(['financial'])->where('userfinancial.status', '<', 2)->select();
        if ($data) {
            Db::startTrans();
            try {
                foreach ($data as $k => $v) {
                    if ($v->financial) {
                        $userCount = User::where(['id'=>$v->user_id])->count();
                        if($userCount){
                            $years_rate     = $v->financial->years_rate / 100;
                            $jishu          = floor($v->principal * $years_rate / 360 * $v->all_day);
                            $user_money     = floor($jishu / $v->all_day);
                            $remaining_day  = $v->all_day - $v->claimed_day;
                            if ($remaining_day <= 1) {
                                $v->status  = 2;
                                $user_money = floor($jishu - $v->claimed_day * $user_money);
                            }
                            $v->claimed_day += 1;
                            if ($v->status == 0) {
                                $v->status = 1;
                            }
                            WalletService::change($v->user_id, 'score', $user_money, 'interest', $v->id,
                                $v->financial->title.'利息');
                            if ($v->status == 2) {
                                WalletService::change($v->user_id, 'score', $v->principal, 'return_principal', $v->id,
                                    '本金返还');
                            }
                            $v->save();
                        }
                    }
                }
                Db::commit();
                echo "返利成功";
            } catch (HttpResponseException $e) {
                Db::rollback();
                $data    = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                echo $message;
            }
        }
    }
}
